<template>
  <nav class="navbar">
    <!-- 项目logo和倒计时 -->
    <div class="logo-container">
      <div class="logo-box">
        <!-- 动态logo显示 -->
        <div v-if="systemSettings?.systemLogo" class="logo-image">
          <img :src="getFullImageUrl(systemSettings.systemLogo)" :alt="systemSettings.systemName || '考研真题训练系统'" />
        </div>
        <el-icon v-else class="logo-icon"><Reading /></el-icon>
        
        <span class="logo-text">{{ systemSettings?.systemName || '考研真题训练系统' }}</span>
      </div>
      <div class="exam-counter">
        距离考研{{ daysToExam }}天！已坚持{{ accountAgeDays || 0 }}天！
      </div>
    </div>
    
    <!-- 首页 -->
    <router-link to="/home" class="nav-item">
      <el-icon><HomeFilled /></el-icon>
      <span>首页</span>
    </router-link>
    
    <!-- 真题训练 -->
    <div class="nav-group" @mouseenter="showSubMenu('training')" @mouseleave="hideSubMenu('training')">
      <span class="nav-item">
        <el-icon><Notebook /></el-icon>
        <span>真题训练</span>
        <el-icon class="arrow-icon"><ArrowDown /></el-icon>
      </span>
      <div class="sub-menu" v-show="activeMenu === 'training'">
        <router-link to="/training/record" @click="hideSubMenu('training')">
          <el-icon><List /></el-icon>
          <span>训练记录</span>
        </router-link>
        <router-link to="/training/mock-exam" @click="hideSubMenu('training')">
          <el-icon><EditPen /></el-icon>
          <span>模拟考试</span>
        </router-link>
        <router-link to="/training/daily-practices" @click="hideSubMenu('training')">
          <el-icon><AlarmClock /></el-icon>
          <span>每日一练</span>
        </router-link>
      </div>
    </div>
    
    <!-- 学习计划 -->
    <div class="nav-group" @mouseenter="showSubMenu('study')" @mouseleave="hideSubMenu('study')">
      <span class="nav-item">
        <el-icon><Calendar /></el-icon>
        <span>学习计划</span>
        <el-icon class="arrow-icon"><ArrowDown /></el-icon>
      </span>
      <div class="sub-menu" v-show="activeMenu === 'study'">
        <router-link to="/study-plan/today" @click="hideSubMenu('study')">
          <el-icon><Sunny /></el-icon>
          <span>今日计划</span>
        </router-link>
        <router-link to="/study-plan/create" @click="hideSubMenu('study')">
          <el-icon><Plus /></el-icon>
          <span>制定计划</span>
        </router-link>
      </div>
    </div>
    
    <!-- 收藏夹 -->
    <div class="nav-group" @mouseenter="showSubMenu('favorites')" @mouseleave="hideSubMenu('favorites')">
      <span class="nav-item">
        <el-icon><Star /></el-icon>
        <span>收藏夹</span>
        <el-icon class="arrow-icon"><ArrowDown /></el-icon>
      </span>
      <div class="sub-menu" v-show="activeMenu === 'favorites'">
        <router-link to="/favorites/questions" @click="hideSubMenu('favorites')">
          <el-icon><Collection /></el-icon>
          <span>我的题库</span>
        </router-link>
        <router-link to="/favorites/wrong-questions" @click="hideSubMenu('favorites')">
          <el-icon><Warning /></el-icon>
          <span>错题本</span>
        </router-link>
      </div>
    </div>
    
    <!-- 发现 -->
    <div class="nav-group" @mouseenter="showSubMenu('discover')" @mouseleave="hideSubMenu('discover')">
      <span class="nav-item">
        <el-icon><Search /></el-icon>
        <span>发现</span>
        <el-icon class="arrow-icon"><ArrowDown /></el-icon>
      </span>
      <div class="sub-menu" v-show="activeMenu === 'discover'">
        <router-link to="/discover/ranking" @click="hideSubMenu('discover')">
          <el-icon><Trophy /></el-icon>
          <span>排行榜</span>
        </router-link>
        <router-link to="/discover/community" @click="hideSubMenu('discover')">
          <el-icon><ChatLineRound /></el-icon>
          <span>社区论坛</span>
        </router-link>
      </div>
    </div>
    
    <!-- 数据统计 -->
    <router-link to="/statistics" class="nav-item">
      <el-icon><DataAnalysis /></el-icon>
      <span>数据统计</span>
    </router-link>
    
    <!-- 用户 -->
    <div class="nav-group" @mouseenter="showSubMenu('user')" @mouseleave="hideSubMenu('user')">
      <span v-if="!username" class="nav-item">
        <el-icon><User /></el-icon>
        <span>登录/注册</span>
      </span>
      <span v-else class="nav-item">
        <el-avatar :size="24" :src="userAvatar" />
        <span class="username">{{ username }}</span>
      </span>
      <div class="sub-menu" v-show="activeMenu === 'user'">
        <router-link v-if="username" to="/user/profile" @click="hideSubMenu('user')">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </router-link>
        <router-link v-else to="/login" @click="hideSubMenu('user')">
          <el-icon><UserFilled /></el-icon>
          <span>登录</span>
        </router-link>
        <a v-if="username" href="#" @click.prevent="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出</span>
        </a>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { AlarmClock } from '@element-plus/icons-vue'
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import axios from 'axios';
import {
  HomeFilled,
  Notebook,
  List,
  EditPen,
  Calendar,
  Sunny,
  Plus,
  Star,
  Collection,
  Warning,
  Search,
  Trophy,
  ChatLineRound,
  DataAnalysis,
  User,
  UserFilled,
  SwitchButton,
  ArrowDown,
  Reading
} from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();

userStore.initialize();
const username = computed(() => userStore.username);
const userId = computed(() => userStore.userId);
const userAvatar = computed(() => userStore.avatar || '');
const activeMenu = ref(null);

// 系统设置数据
const systemSettings = ref(null);
const loading = ref(false);

// 动态计算倒计时
const daysToExam = ref(0);
const accountAgeDays = ref(null); // 从后端获取的用户账号创建天数

// 考研日期：2025年12月21日
const examDate = new Date('2025-12-21');

// 获取用户账号创建天数
const fetchAccountAge = async () => {
  if (!userId.value) {
    accountAgeDays.value = null;
    return;
  }

  try {
    const response = await axios.get(`/api/insistence-time/user/${userId.value}`);
    if (response.data && response.data.accountAgeDays !== undefined) {
      accountAgeDays.value = response.data.accountAgeDays;
    }
  } catch (error) {
    console.error('获取用户账号天数失败:', error);
    accountAgeDays.value = null;
  }
};

// 获取系统设置
const fetchSystemSettings = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/system/settings');
    systemSettings.value = response.data;
    console.log('系统设置获取成功:', response.data);
  } catch (error) {
    console.error('获取系统设置失败:', error);
    // 如果获取失败，使用默认设置
    systemSettings.value = {
      systemName: '考研真题训练系统',
      systemLogo: null
    };
  } finally {
    loading.value = false;
  }
};

// 获取完整的图片URL
const getFullImageUrl = (systemLogo) => {
  if (!systemLogo) return '';
  
  // 如果已经是完整URL，直接返回
  if (systemLogo.startsWith('http://') || systemLogo.startsWith('https://')) {
    return systemLogo;
  }
  
  // 如果是相对路径，拼接服务器地址
  const baseUrl = window.location.origin; // 获取当前域名
  return baseUrl + systemLogo;
};

// 计算距离考研的天数
const calculateDaysToExam = () => {
  const today = new Date();
  // 将时间设置为当天的开始（00:00:00）
  today.setHours(0, 0, 0, 0);
  examDate.setHours(0, 0, 0, 0);
  
  const timeDiff = examDate.getTime() - today.getTime();
  const daysDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
  
  // 如果考试已过，显示为0
  daysToExam.value = daysDiff > 0 ? daysDiff : 0;
};

// 监听userId变化，当用户登录/登出时重新获取账号天数
watch(userId, (newVal) => {
  if (newVal) {
    fetchAccountAge();
  } else {
    accountAgeDays.value = null;
  }
});

// 定时器ID
let timer = null;

onMounted(async () => {
  // 获取系统设置
  await fetchSystemSettings();
  
  // 初始计算
  calculateDaysToExam();
  
  // 如果用户已登录，获取账号天数
  if (userId.value) {
    await fetchAccountAge();
  }
  
  // 每天0点更新一次倒计时
  // 计算到下一个0点的毫秒数
  const now = new Date();
  const tomorrow = new Date(now);
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0, 0, 0, 0);
  const msUntilMidnight = tomorrow.getTime() - now.getTime();
  
  // 在下一个0点时执行第一次更新，然后每24小时执行一次
  setTimeout(() => {
    calculateDaysToExam();
    timer = setInterval(calculateDaysToExam, 24 * 60 * 60 * 1000); // 每24小时执行一次
  }, msUntilMidnight);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

const showSubMenu = (menu) => { activeMenu.value = menu; };
const hideSubMenu = (menu) => { if (activeMenu.value === menu) activeMenu.value = null; };
const handleLogout = () => { userStore.clearUser(); router.push('/login'); };
</script>


<style scoped>
.navbar {
  display: flex;
  background: white;
  color: #2c3e50;
  padding: 0 24px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 64px;
  z-index: 1000;
  gap: 5px;
  box-sizing: border-box;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  border-bottom: 1px solid #e0e0e0;
}

.logo-container {
  display: flex;
  align-items: center;
  margin-right: 35px;
  height: 100%;
}

.logo-box {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  height: 48px;
  margin-right: 20px;
  transition: all 0.3s ease;
  border-radius: 6px;
}

.logo-box:hover {
  transform: translateY(-0.5px);
  background: rgba(0, 123, 255, 0.04);
}

.logo-image {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  overflow: hidden;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.logo-image:hover {
  transform: scale(1.02);
}

.logo-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.logo-icon {
  font-size: 28px;
  color: #007bff;
  margin-right: 12px;
  transition: all 0.3s ease;
}

.logo-icon:hover {
  transform: scale(1.05);
  color: #0056b3;
}

.logo-text {
  font-size: 20px;
  font-weight: 600;
  color: #007bff;
  letter-spacing: 0.5px;
  transition: all 0.3s ease;
}

.exam-counter {
  font-size: 13px;
  color: #007bff;
  background: rgba(0, 123, 255, 0.1);
  padding: 8px 14px;
  border-radius: 16px;
  border: 1px solid rgba(0, 123, 255, 0.2);
  font-weight: 500;
  white-space: nowrap;
  transition: all 0.3s ease;
}

.exam-counter:hover {
  background: rgba(0, 123, 255, 0.12);
  transform: translateY(-0.5px);
  border-color: rgba(0, 123, 255, 0.25);
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 0 14px;
  height: 100%;
  position: relative;
  cursor: pointer;
  text-decoration: none;
  color: #495057;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  margin: 0 1px;
  transition: all 0.2s ease;
}

.nav-item:hover {
  background: rgba(0, 123, 255, 0.06);
  color: #007bff;
  transform: translateY(-0.5px);
}

.nav-item .el-icon {
  margin-right: 6px;
  font-size: 16px;
  transition: all 0.2s ease;
  color: #6c757d;
}

.nav-item:hover .el-icon {
  color: #007bff;
}

.arrow-icon {
  margin-left: 4px;
  font-size: 12px !important;
  transition: all 0.2s ease;
  color: #6c757d !important;
}

.nav-group:hover .arrow-icon {
  transform: rotate(180deg);
  color: #007bff !important;
}

.nav-group {
  position: relative;
  height: 100%;
}

.nav-group::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  height: 2px;
  background: transparent;
  z-index: 1000;
}

.sub-menu {
  display: flex;
  flex-direction: column;
  position: absolute;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  min-width: 160px;
  top: 100%;
  left: 0;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  padding: 6px;
  z-index: 1001;
  margin-top: 0;
}

.sub-menu::before {
  content: '';
  position: absolute;
  top: -6px;
  left: 20px;
  width: 12px;
  height: 12px;
  background: white;
  border: 1px solid #e0e0e0;
  border-right: none;
  border-bottom: none;
  transform: rotate(45deg);
}

.sub-menu a {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  text-decoration: none;
  color: #495057;
  white-space: nowrap;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s ease;
  border-radius: 6px;
  margin: 1px 0;
  line-height: 1.4;
}

.sub-menu a:hover {
  background: rgba(0, 123, 255, 0.08);
  color: #007bff;
  transform: translateX(4px);
}

.sub-menu .el-icon {
  color: #6c757d;
  margin-right: 8px;
  font-size: 14px;
  transition: all 0.2s ease;
}

.sub-menu a:hover .el-icon {
  color: #007bff;
}

.router-link-active {
  background: rgba(0, 123, 255, 0.1) !important;
  color: #007bff !important;
  font-weight: 600;
  position: relative;
}

.router-link-active::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 3px;
  background: #007bff;
  border-radius: 2px;
}

.router-link-active .el-icon {
  color: #007bff !important;
}

.username {
  margin-left: 8px;
  font-weight: 500;
  color: #495057;
}

.el-avatar {
  background: #007bff;
  border: 2px solid rgba(0, 123, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .logo-container {
    margin-right: 25px;
  }
  
  .exam-counter {
    font-size: 12px;
    padding: 6px 12px;
  }
  
  .nav-item {
    font-size: 13px;
    padding: 0 14px;
  }
}

@media (max-width: 768px) {
  .navbar {
    padding: 0 15px;
  }
  
  .logo-text {
    font-size: 16px;
  }
  
  .logo-image {
    width: 28px;
    height: 28px;
    margin-right: 10px;
  }
  
  .logo-image img {
    width: 24px;
    height: 24px;
  }
  
  .logo-box {
    padding: 6px 12px;
    height: 40px;
    margin-right: 15px;
  }
  
  .exam-counter {
    display: none; /* 在小屏幕上隐藏倒计时 */
  }
  
  .nav-item {
    font-size: 12px;
    padding: 0 12px;
  }
}

@media (max-width: 480px) {
  .navbar {
    padding: 0 10px;
    gap: 2px;
  }
  
  .logo-text {
    font-size: 14px;
  }
  
  .logo-image {
    width: 24px;
    height: 24px;
    margin-right: 8px;
  }
  
  .logo-image img {
    width: 20px;
    height: 20px;
  }
  
  .nav-item {
    padding: 0 8px;
  }
  
  .nav-item span:not(.username) {
    display: none;
  }
  
  .nav-item .el-icon {
    margin-right: 0;
  }
}

/* 动画效果 */
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.sub-menu {
  animation: slideDown 0.2s ease-out;
}
</style>